// src/store/modules/chat.js
// 基于现有逻辑优化的聊天状态管理模块
import service from "../../utils/request";
import { getToken } from "../../utils/auth";

// 工具函数：判断消息是否匹配
function isMessageMatch(optimisticMessage, realMessage) {
  const contentMatch = optimisticMessage.content === realMessage.content;
  const timeMatch =
    Math.abs(
      new Date(optimisticMessage.createTime) - new Date(realMessage.createTime)
    ) < 5000; // 5秒内
  const receiverMatch =
    optimisticMessage.othersUserId === realMessage.othersUserId;

  return contentMatch && timeMatch && receiverMatch;
}

// 工具函数：安全地获取消息
function getMessagesSafely(state, chatId) {
  if (!state.messages || typeof state.messages !== "object") {
    console.log('getMessagesSafely - no messages or invalid messages object:', { messages: state.messages, chatId });
    return [];
  }
  const messages = state.messages[chatId] || [];
  console.log('getMessagesSafely - chatId:', chatId, 'messages:', messages);
  return messages;
}

const state = {
  // 当前聊天信息（保持与现有逻辑一致）
  currentChat: {
    friendshipId: null,
    remark: null,
    type: null, // 0: 群聊, 1: 单聊
    groupChatCount: 0,
  },

  // 当前聊天ID（用于消息管理）
  currentChatId: null,

  // 消息存储 - 按聊天ID分组（使用普通对象而不是Map，避免序列化问题）
  messages: {},

  // 消息ID映射表（优化查找性能）
  messageIdMap: {},

  // 乐观消息映射表
  optimisticMessageMap: {},

  // 聊天状态
  isOnline: true,
  isSending: false,

  // 未读消息数量
  unreadCounts: {},

  // 消息发送状态
  sendingMessages: [],

  // 增量同步相关
  lastSyncTime: 0,
  syncTimer: null,

  // WebSocket连接状态
  isConnected: false,

  // 自动滚动标志
  shouldScroll: false,

  // 消息处理队列
  messageQueue: [],
};

const mutations = {
  // 设置当前聊天（保持现有逻辑）
  SET_CURRENT_CHAT(state, chatInfo) {
    state.currentChat = { ...chatInfo };
    state.currentChatId = chatInfo.friendshipId;
  },

  // 设置当前聊天ID
  SET_CURRENT_CHAT_ID(state, chatId) {
    state.currentChatId = chatId;
  },

  // 设置在线状态
  SET_ONLINE_STATUS(state, isOnline) {
    state.isOnline = isOnline;
  },

  // 设置发送状态
  SET_SENDING_STATUS(state, isSending) {
    state.isSending = isSending;
  },

  // 设置连接状态
  SET_CONNECTION_STATUS(state, isConnected) {
    state.isConnected = isConnected;
  },

  // 设置自动滚动标志
  SET_SHOULD_SCROLL(state, shouldScroll) {
    state.shouldScroll = shouldScroll;
  },

  // 批量添加消息（优化性能）
  BATCH_ADD_MESSAGES(state, messages) {
    if (!Array.isArray(messages) || messages.length === 0) return;

    // 按聊天ID分组消息
    const groupedMessages = messages.reduce((groups, message) => {
      const chatId = message.chatId;
      if (!groups[chatId]) {
        groups[chatId] = [];
      }
      groups[chatId].push(message);
      return groups;
    }, {});

    // 批量更新每个聊天的消息
    Object.entries(groupedMessages).forEach(([chatId, chatMessages]) => {
      if (!state.messages[chatId]) {
        state.messages[chatId] = [];
      }
      
      // 批量添加消息
      state.messages[chatId].push(...chatMessages);
      
      // 更新消息ID映射
      chatMessages.forEach((message, index) => {
        state.messageIdMap[message.id] = {
          chatId,
          index: state.messages[chatId].length - chatMessages.length + index,
        };
      });
    });
  },

  // 更新未读计数
  UPDATE_UNREAD_COUNT(state, { chatId, increment = 1 }) {
    if (!state.unreadCounts[chatId]) {
      state.unreadCounts[chatId] = 0;
    }
    state.unreadCounts[chatId] += increment;
  },

  // 重置未读计数
  RESET_UNREAD_COUNT(state, chatId) {
    state.unreadCounts[chatId] = 0;
  },

  // 添加消息到指定聊天
  ADD_MESSAGE(state, { chatId, message }) {
    if (!state.messages || typeof state.messages !== "object") {
      state.messages = {};
    }

    if (!state.messages[chatId]) {
      state.messages[chatId] = [];
    }

    const messages = state.messages[chatId];
    messages.push(message);

    // 更新消息ID映射
    state.messageIdMap[message.id] = {
      chatId,
      index: messages.length - 1,
    };
  },

  // 更新消息
  UPDATE_MESSAGE(state, { chatId, messageId, updates }) {
    const messages = getMessagesSafely(state, chatId);
    if (messages && messages.length > 0) {
      const index = messages.findIndex((msg) => msg.id === messageId);
      if (index !== -1) {
        Object.assign(messages[index], updates);
      }
    }
  },

  // 替换乐观消息
  REPLACE_OPTIMISTIC_MESSAGE(state, { chatId, tempId, realMessage }) {
    const messages = getMessagesSafely(state, chatId);
    if (messages && messages.length > 0) {
      const index = messages.findIndex((msg) => msg.tempId === tempId);
      if (index !== -1) {
        // 替换消息
        messages[index] = { ...realMessage, isSendSuccessfully: 1 };

        // 更新映射表
        state.messageIdMap[realMessage.id] = { chatId, index };
        delete state.messageIdMap[messages[index].tempId];

        // 从乐观消息映射中移除
        delete state.optimisticMessageMap[tempId];
      }
    }
  },

  // 设置消息列表
  SET_MESSAGES(state, { chatId, messages }) {
    console.log('SET_MESSAGES mutation - chatId:', chatId, 'messages:', messages);
    if (!state.messages || typeof state.messages !== "object") {
      state.messages = {};
    }

    state.messages[chatId] = [...messages];
    console.log('SET_MESSAGES mutation - after setting, state.messages:', state.messages);

    // 重建消息ID映射
    state.messageIdMap = {};
    messages.forEach((msg, index) => {
      state.messageIdMap[msg.id] = { chatId, index };
    });
  },

  // 追加消息到列表开头（用于分页加载）
  PREPEND_MESSAGES(state, { chatId, messages }) {
    if (!state.messages || typeof state.messages !== "object") {
      state.messages = {};
    }

    if (!state.messages[chatId]) {
      state.messages[chatId] = [];
    }

    // 将新消息添加到开头
    state.messages[chatId] = [...messages, ...state.messages[chatId]];

    // 重建消息ID映射
    state.messageIdMap = {};
    state.messages[chatId].forEach((msg, index) => {
      state.messageIdMap[msg.id] = { chatId, index };
    });
  },

  // 追加消息到列表末尾（用于新消息）
  APPEND_MESSAGE(state, { chatId, message }) {
    if (!state.messages || typeof state.messages !== "object") {
      state.messages = {};
    }

    if (!state.messages[chatId]) {
      state.messages[chatId] = [];
    }

    state.messages[chatId].push(message);

    // 更新消息ID映射
    const index = state.messages[chatId].length - 1;
    state.messageIdMap[message.id] = { chatId, index };
  },

  // 更新消息（用于撤回、编辑等）
  UPDATE_MESSAGE_BY_ID(state, { chatId, messageId, updates }) {
    const messages = getMessagesSafely(state, chatId);
    if (messages && messages.length > 0) {
      const index = messages.findIndex((msg) => msg.id === messageId);
      if (index !== -1) {
        Object.assign(messages[index], updates);
      }
    }
  },

  // 清除指定聊天的消息
  CLEAR_MESSAGES(state, chatId) {
    if (state.messages && state.messages[chatId]) {
      delete state.messages[chatId];
    }
  },

  // 设置未读数量
  SET_UNREAD_COUNT(state, { chatId, count }) {
    state.unreadCounts[chatId] = count;
  },

  // 添加发送中的消息
  ADD_SENDING_MESSAGE(state, messageId) {
    if (!state.sendingMessages.includes(messageId)) {
      state.sendingMessages.push(messageId);
    }
  },

  // 移除发送中的消息
  REMOVE_SENDING_MESSAGE(state, messageId) {
    const index = state.sendingMessages.indexOf(messageId);
    if (index > -1) {
      state.sendingMessages.splice(index, 1);
    }
  },

  // 设置最后同步时间
  SET_LAST_SYNC_TIME(state, time) {
    state.lastSyncTime = time;
  },

  // 更新消息状态
  UPDATE_MESSAGE_STATUS(state, { tempId, status }) {
    // 更新乐观消息的状态
    if (state.optimisticMessageMap[tempId]) {
      state.optimisticMessageMap[tempId].isSendSuccessfully = status;
    }
    
    // 更新发送中的消息列表
    if (status === 1) { // 发送成功
      const index = state.sendingMessages.indexOf(tempId);
      if (index > -1) {
        state.sendingMessages.splice(index, 1);
      }
    }
  },
};

const actions = {
  // 添加乐观消息
  addOptimisticMessage({ commit }, { chatId, message }) {
    const optimisticMessage = {
      ...message,
      tempId: message.tempId || `temp_${Date.now()}_${Math.random()}`,
      isSendSuccessfully: 0, // 0: 发送中, 1: 成功, 2: 失败
      createTime: new Date().toISOString()
    };
    
    commit('ADD_MESSAGE', { chatId, message: optimisticMessage });
    commit('ADD_SENDING_MESSAGE', optimisticMessage.tempId);
  },
  // 更新消息状态
  updateMessageStatus({ commit, state }, { tempId, status, realMessage, error }) {
    const chatId = state.currentChatId;
    
    if (status === 'success' && realMessage) {
      // 替换乐观消息为真实消息
      commit('REPLACE_OPTIMISTIC_MESSAGE', {
        chatId,
        tempId,
        realMessage
      });
    } else {
      // 更新消息状态
      commit('UPDATE_MESSAGE', {
        chatId,
        messageId: tempId,
        updates: {
          isSendSuccessfully: status === 'success' ? 1 : 2,
          error: error || null
        }
      });
    }
    
    // 移除发送中状态
    commit('REMOVE_SENDING_MESSAGE', tempId);
  },
  // 设置当前聊天（保持现有逻辑）
  setCurrentChat({ commit }, chatInfo) {
    commit("SET_CURRENT_CHAT", chatInfo);
  },

  // 加载聊天消息（保持现有API调用）
  async loadChatMessages(
    { commit, state },
    { chatId, chatType = "single", page = 1, size = 50 }
  ) {
    try {
      const url =
        chatType === "single"
          ? "friend_chat/chatMessageList"
          : "group_chat/groupList";

      const params =
        chatType === "single"
          ? { friendId: chatId, page, size }
          : { groupChatId: chatId, page, size };

      const res = await service({
        method: "get",
        url,
        params,
      });

      if (res.data) {
        commit("SET_MESSAGES", { chatId, messages: res.data });
        commit("SET_LAST_SYNC_TIME", Date.now());
      }

      return res.data || [];
    } catch (error) {
      console.error("加载聊天消息失败:", error);
      throw error;
    }
  },

  // 发送消息
  async sendMessage({ commit, state, dispatch }, messageData) {
    if (state.isSending) return;

    console.log("messageData--->",messageData)
    commit("SET_SENDING_STATUS", true);

    try {
      // 1. 创建乐观消息
      const optimisticMessage = dispatch(
        "createOptimisticMessage",
        messageData
      );

      // 2. 立即显示消息
      commit("ADD_MESSAGE", {
        chatId: state.currentChatId,
        message: optimisticMessage,
      });

      console.log("optimisticMessage------>",JSON.stringify(optimisticMessage))
      // 3. 发送到服务器
      // const message = {
      //   action: messageData.chatType === 1 ? 10003 : 10006,
      //   token: getToken(),
      //   receiverId:
      //     messageData.chatType === 1 ? state.currentChatId : undefined,
      //   groupChatId:
      //     messageData.chatType === 0 ? state.currentChatId : undefined,
      //   content: messageData.content,
      //   extend: messageData.extend || 0,
      //   quoteId: messageData.quoteId,
      //   atUserIds: messageData.atUserIds || [],
      // };

      // 通过WebSocket发送（保持现有逻辑）
      // if (window.socket && window.socket.send) {
      //   window.socket.send(message);
      // }

      //通过http发送消息到后台

      service({
        method: "post",
        url: "friend_chat/send",
        data: optimisticMessage,
      }).then((res) => {
        if (res.code === 200) {
          console.error("发送消息失败res:", res);
        }
      });
      // 4. 设置发送中状态
      commit("ADD_SENDING_MESSAGE", optimisticMessage.tempId);
    } catch (error) {
      console.error("发送消息失败:", error);
      throw error;
    } finally {
      commit("SET_SENDING_STATUS", false);
    }
  },

  // 创建乐观消息
  createOptimisticMessage({ state, rootGetters }, messageData) {
    const userInfo = rootGetters.userLogin;
    const tempId = `temp_${Date.now()}_${Math.random()}`;
    return {
      id: tempId,
      tempId: tempId,
      content: messageData.content,
      messageType: messageData.extend || 0,
      createTime: new Date().toISOString(),
      isMyselfMsg: true,
      myUserId: userInfo.id,
      myNickName: userInfo.nickName,
      myAvatar: userInfo.avatar,
      othersUserId: state.currentChatId,
      isSendSuccessfully: 0, // 0: 发送中, 1: 成功, 2: 失败
      isRead: 0,
      quoteId: messageData.quoteId,
      quoteData: messageData.quoteData,
      atUserIds: messageData.atUserIds || [],
    };
  },

  // 接收消息（保持现有逻辑）
  receiveMessage({ commit, state, dispatch }, message) {
    const chatId = message.othersUserId || message.groupChatId;

    // 检查是否是乐观消息的确认
    const optimisticMessage = dispatch("findOptimisticMessage", message);

    if (optimisticMessage) {
      // 替换乐观消息
      commit("REPLACE_OPTIMISTIC_MESSAGE", {
        chatId,
        tempId: optimisticMessage.tempId,
        realMessage: message,
      });
    } else {
      // 添加新消息
      commit("ADD_MESSAGE", { chatId, message });
    }

    // 更新未读数量
    if (!message.isMyselfMsg) {
      const currentCount = state.unreadCounts[chatId] || 0;
      commit("SET_UNREAD_COUNT", { chatId, count: currentCount + 1 });
    }
  },

  // 查找乐观消息
  findOptimisticMessage({ state }, realMessage) {
    for (const tempId in state.optimisticMessageMap) {
      const optimisticMessage = state.optimisticMessageMap[tempId];
      if (isMessageMatch(optimisticMessage, realMessage)) {
        return optimisticMessage;
      }
    }
    return null;
  },

  // 更新消息状态
  updateMessageStatus({ commit, state }, { tempId, status }) {
    const messages = getMessagesSafely(state, state.currentChatId);
    if (messages && messages.length > 0) {
      const index = messages.findIndex((msg) => msg.tempId === tempId);
      if (index !== -1) {
        commit("UPDATE_MESSAGE", {
          chatId: state.currentChatId,
          messageId: tempId,
          updates: { isSendSuccessfully: status },
        });

        if (status === 1 || status === 2) {
          commit("REMOVE_SENDING_MESSAGE", tempId);
        }
      }
    }
  },

  // 标记消息已读
  markMessagesAsRead({ commit, state }, chatId) {
    commit("SET_UNREAD_COUNT", { chatId, count: 0 });
  },

  // 设置在线状态
  setOnlineStatus({ commit }, isOnline) {
    commit("SET_ONLINE_STATUS", isOnline);
  },

  // 同步消息到Vuex（HTTP请求成功后调用）
  syncMessagesToStore({ commit }, { chatId, messages }) {
    commit("SET_MESSAGES", { chatId, messages });
    commit("SET_LAST_SYNC_TIME", Date.now());
  },

  // 分页加载消息
  async loadMoreMessages({ commit, state }, { chatId, page, size = 50, chatType = "single" }) {
    try {
      const url = chatType === "single" 
        ? "friend_chat/chatMessageList" 
        : "group_chat/groupList";

      const params = chatType === "single"
        ? { friendId: chatId, currentPage: page, size }
        : { groupChatId: chatId, currentPage: page, size };

      const res = await service({
        method: "get",
        url,
        params,
      });

      if (res.data && res.data.length > 0) {
        // 将新消息添加到开头
        commit("PREPEND_MESSAGES", { chatId, messages: res.data });
        return res.data;
      }

      return [];
    } catch (error) {
      console.error("加载更多消息失败:", error);
      throw error;
    }
  },

  // 接收实时消息
  receiveRealTimeMessage({ commit, state, dispatch }, message) {
    const chatId = message.othersUserId || message.groupChatId;
    
    // 检查是否是乐观消息的确认
    const optimisticMessage = dispatch("findOptimisticMessage", message);
    
    if (optimisticMessage) {
      // 替换乐观消息
      commit("REPLACE_OPTIMISTIC_MESSAGE", {
        chatId,
        tempId: optimisticMessage.tempId,
        realMessage: message,
      });
    } else {
      // 添加新消息
      commit("APPEND_MESSAGE", { chatId, message });
    }

    // 更新未读数量
    if (!message.isMyselfMsg) {
      const currentCount = state.unreadCounts[chatId] || 0;
      commit("SET_UNREAD_COUNT", { chatId, count: currentCount + 1 });
    }
  },

  // 撤回消息
  retractMessage({ commit }, { chatId, messageId }) {
    commit("UPDATE_MESSAGE_BY_ID", {
      chatId,
      messageId,
      updates: { isRetracted: true }
    });
  },

  // 编辑消息
  editMessage({ commit }, { chatId, messageId, newContent }) {
    commit("UPDATE_MESSAGE_BY_ID", {
      chatId,
      messageId,
      updates: { 
        content: newContent,
        isEdited: true,
        editTime: new Date().toISOString()
      }
    });
  },

  // 标记消息已读
  markMessageAsRead({ commit }, { chatId, messageId }) {
    commit("UPDATE_MESSAGE_BY_ID", {
      chatId,
      messageId,
      updates: { isRead: 1 }
    });
  },

  // 清除聊天记录
  clearChatHistory({ commit }, chatId) {
    commit("CLEAR_MESSAGES", chatId);
    commit("SET_UNREAD_COUNT", { chatId, count: 0 });
  },
};

const getters = {
  // 当前聊天信息
  currentChat: (state) => state.currentChat,

  // 当前聊天ID
  currentChatId: (state) => state.currentChatId,

  // 获取指定聊天的消息
  getMessages: (state) => (chatId) => {
    const messages = getMessagesSafely(state, chatId);
    console.log('getMessages getter - chatId:', chatId, 'messages:', messages);
    return messages;
  },

  // 当前聊天的消息
  currentMessages: (state) => {
    return getMessagesSafely(state, state.currentChatId);
  },

  // 在线状态
  isOnline: (state) => state.isOnline,

  // 发送状态
  isSending: (state) => state.isSending,

  // 未读消息数量
  unreadCount: (state) => (chatId) => {
    return state.unreadCounts[chatId] || 0;
  },

  // 总未读数量
  totalUnreadCount: (state) => {
    return Object.values(state.unreadCounts).reduce(
      (total, count) => total + count,
      0
    );
  },

  // 发送中的消息
  sendingMessages: (state) => state.sendingMessages,

  // 最后同步时间
  lastSyncTime: (state) => state.lastSyncTime,

  // 获取消息总数
  getMessageCount: (state) => (chatId) => {
    const messages = getMessagesSafely(state, chatId);
    return messages.length;
  },

  // 获取最新消息
  getLatestMessage: (state) => (chatId) => {
    const messages = getMessagesSafely(state, chatId);
    return messages.length > 0 ? messages[messages.length - 1] : null;
  },

  // 获取指定消息
  getMessageById: (state) => (chatId, messageId) => {
    const messages = getMessagesSafely(state, chatId);
    return messages.find(msg => msg.id === messageId);
  },

  // 检查是否有未读消息
  hasUnreadMessages: (state) => (chatId) => {
    return (state.unreadCounts[chatId] || 0) > 0;
  },

  // 获取发送中的消息
  getSendingMessages: (state) => (chatId) => {
    const messages = getMessagesSafely(state, chatId);
    return messages.filter(msg => msg.isSendSuccessfully === 0);
  },

  // 获取失败的消息
  getFailedMessages: (state) => (chatId) => {
    const messages = getMessagesSafely(state, chatId);
    return messages.filter(msg => msg.isSendSuccessfully === 2);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
